<!-- eslint-disable vue/no-deprecated-slot-attribute -->
<!-- eslint-disable vue/no-deprecated-slot-scope-attribute -->
<!-- eslint-disable vue/no-deprecated-v-bind-sync -->
<!-- eslint-disable no-unused-vars -->
<template>
  <div class="info-entry-container">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/farmer' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>信息录入管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 产品信息列表 -->
    <el-card class="content-card">
      <div slot="header" class="card-header">
        <span>产品信息列表</span>
        <el-button type="primary" size="small" @click="openAddDialog" style="margin-right: 500px">新增产品</el-button>
      </div>

      <!-- 搜索区域 -->
<!--      <el-row :gutter="20" class="search-area">-->
<!--        <el-col :span="6">-->
<!--          <el-input placeholder="请输入产品名称" v-model="queryParams.productName" clearable>-->
<!--            <el-button slot="append" icon="el-icon-search" @click="searchProduct"></el-button>-->
<!--          </el-input>-->
<!--        </el-col>-->
<!--        <el-col :span="6">-->
<!--          <el-input placeholder="请输入批次号" v-model="queryParams.batchNumber" clearable>-->
<!--            <el-button slot="append" icon="el-icon-search" @click="searchProduct"></el-button>-->
<!--          </el-input>-->
<!--        </el-col>-->
<!--        <el-col :span="6">-->
<!--          <el-date-picker-->
<!--            v-model="queryParams.dateRange"-->
<!--            type="daterange"-->
<!--            range-separator="至"-->
<!--            start-placeholder="种植开始日期"-->
<!--            end-placeholder="种植结束日期"-->
<!--            value-format="yyyy-MM-dd"-->
<!--            style="width: 100%;">-->
<!--          </el-date-picker>-->
<!--        </el-col>-->
<!--        <el-col :span="6">-->
<!--          <el-button type="primary" @click="searchProduct">搜索</el-button>-->
<!--          <el-button @click="resetQuery">重置</el-button>-->
<!--        </el-col>-->
<!--      </el-row>-->

      <!-- 表格 -->
      <el-table :data="productList" border stripe style="width: 100%" v-loading="loading">
        <el-table-column type="index" label="#" width="50"></el-table-column>
        <el-table-column prop="name" label="产品名称" width="120"></el-table-column>
<!--        <el-table-column prop="productCode" label="产品编码" width="120"></el-table-column>-->
        <el-table-column prop="batchNumber" label="批次号" width="120"></el-table-column>
        <el-table-column label="产品图片" width="120">
          <template v-slot="scope">
            <div class="table-image-container" v-if="scope.row.imageUrl">
              <img
                :src="scope.row.imageUrl"
                class="table-product-image"
                @click="showLargeImage(scope.row.imageUrl)"
                :title="'点击查看大图'"
                alt="产品图片"
                @error="handleImageError">
            </div>
            <span v-else>暂无图片</span>
          </template>
        </el-table-column>
        <el-table-column label="生产日期" width="120">
          <template v-slot="scope">
            {{ scope.row.plantingDate || '' }}
          </template>
        </el-table-column>
<!--        <el-table-column label="采收日期" width="120">-->
<!--          <template v-slot="scope">-->
<!--            {{ scope.row.harvestDate || '' }}-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column label="厂家名称" width="120">
          <template v-slot="scope">
            {{ scope.row.storageMethods || '' }}
          </template>
        </el-table-column>
        <el-table-column label="产地" width="120">
          <template v-slot="scope">
            {{ scope.row.productionStandard || '' }}
          </template>
        </el-table-column>
<!--        <el-table-column label="存储方式" width="120">-->
<!--          <template v-slot="scope">-->
<!--            {{ scope.row.storageMethods || '' }}-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column label="施肥情况" width="120">-->
<!--          <template v-slot="scope">-->
<!--            {{ scope.row.fertilizerUsed || '' }}-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column label="用药情况" width="120">-->
<!--          <template v-slot="scope">-->
<!--            {{ scope.row.pesticideUsed || '' }}-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column label="生产标准" width="120">-->
<!--          <template v-slot="scope">-->
<!--            {{ scope.row.productionStandard || '' }}-->
<!--          </template>-->
<!--        </el-table-column>-->

        <el-table-column label="操作" width="200">
          <template v-slot="scope">
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" size="mini" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
<!--      <el-pagination-->
<!--        @size-change="handleSizeChange"-->
<!--        @current-change="handleCurrentChange"-->
<!--        :current-page="queryParams.pageNum"-->
<!--        :page-sizes="[10, 20, 50, 100]"-->
<!--        :page-size="queryParams.pageSize"-->
<!--        layout="total, sizes, prev, pager, next, jumper"-->
<!--        :total="total">-->
<!--      </el-pagination>-->
      <!-- 优化后的分页 -->
      <el-pagination
          :current-page.sync="queryParams.pageNum"
          :page-size.sync="queryParams.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          style="margin-top: 20px; text-align: center">
      </el-pagination>



    </el-card>

    <!-- 新增/编辑产品信息对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="60%" @close="resetForm">
      <el-form :model="productForm" :rules="rules" ref="productFormRef" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="productForm.productName" placeholder="请输入产品名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="批次号" prop="batchNumber">
              <el-input v-model="productForm.batchNumber" placeholder="请输入批次号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="生产日期" prop="plantingDate">
              <el-date-picker
                v-model="productForm.plantingDate"
                type="date"
                placeholder="选择生产日期"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-col>
<!--          <el-col :span="12">-->
<!--            <el-form-item label="采收日期" prop="harvestDate">-->
<!--              <el-date-picker-->
<!--                v-model="productForm.harvestDate"-->
<!--                type="date"-->
<!--                placeholder="选择采收日期"-->
<!--                value-format="yyyy-MM-dd HH:mm:ss"-->
<!--                style="width: 100%;">-->
<!--              </el-date-picker>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
        </el-row>

        <el-row :gutter="20">
<!--          <el-col :span="12">-->
<!--            <el-form-item label="种植面积" prop="plantingArea">-->
<!--              <el-input v-model="productForm.plantingArea" placeholder="请输入种植面积（亩）"></el-input>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="品质等级" prop="qualityLevel">-->
<!--              <el-select v-model="productForm.qualityLevel" placeholder="请选择品质等级" style="width: 100%;">-->
<!--                <el-option label="特级" value="特级"></el-option>-->
<!--                <el-option label="一级" value="一级"></el-option>-->
<!--                <el-option label="二级" value="二级"></el-option>-->
<!--                <el-option label="三级" value="三级"></el-option>-->
<!--              </el-select>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
        </el-row>

<!--        <el-row :gutter="20">-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="施肥情况" prop="fertilizerUsed">-->
<!--              <el-input v-model="productForm.fertilizerUsed" type="textarea" :rows="2" placeholder="请输入施肥情况"></el-input>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="用药情况" prop="pesticideUsed">-->
<!--              <el-input v-model="productForm.pesticideUsed" type="textarea" :rows="2" placeholder="请输入用药情况"></el-input>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--        </el-row>-->

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="厂家名称" prop="storageMethods">
              <el-input v-model="productForm.storageMethods" placeholder="请输入厂家名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地址" prop="productionStandard">
              <el-input v-model="productForm.productionStandard" placeholder="请输入地址"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="产品图片" prop="productImage">
          <el-input
            v-model="productForm.productImage"
            placeholder="请输入产品图片URL链接">
            <template #append>
              <el-button @click="previewImage" :disabled="!productForm.productImage">预览</el-button>
            </template>
          </el-input>
          <div v-if="productForm.productImage" class="image-preview">
            <img :src="productForm.productImage" class="product-image">
          </div>
          <div class="image-tip">请输入有效的图片URL链接</div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitting">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 溯源码展示对话框 -->
    <el-dialog title="产品溯源码" v-model="qrCodeVisible" width="30%" center>
      <div class="qrcode-container" v-loading="qrCodeLoading">
        <div class="qrcode-image" v-if="qrCodeUrl">
          <img :src="qrCodeUrl" alt="产品溯源码">
        </div>
        <div class="qrcode-info" v-if="currentProduct.id">
          <p>产品名称：{{ currentProduct.productName }}</p>
          <p>批次号：{{ currentProduct.batchNumber }}</p>
          <p>生产日期：{{ currentProduct.plantingDate }} 至 {{ currentProduct.harvestDate }}</p>
        </div>
        <div class="qrcode-tip">扫描二维码查看产品详情及溯源信息</div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="downloadQrCode" :disabled="!qrCodeUrl">下载溯源码</el-button>
        <el-button @click="qrCodeVisible = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 图片预览对话框 -->
    <el-dialog title="图片预览" v-model="imagePreviewVisible" width="50%" center>
      <div class="image-preview-container">
        <img :src="previewImageUrl" class="preview-image" alt="图片预览">
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 引入API
import { productAPI, traceCodeAPI, userAPI } from '@/api/api';

export default {
  name: 'InfoEntryView',
  data() {
    return {
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 100,
        // productName: '',
        // batchNumber: '',
        // dateRange: []
      },
      // 总记录数
      total: 0,
      // 产品列表
      productList: [],
      // 对话框显示状态
      dialogVisible: false,
      // 对话框标题
      dialogTitle: '新增产品信息',
      // 表单数据
      productForm: {
        id: null,
        productName: '',
        productCode: '',
        batchNumber: '',
        plantingDate: '',
        harvestDate: '',
        plantingArea: '',
        fertilizerUsed: '',
        pesticideUsed: '',
        storageMethods: '',
        productImage: '',
        productionStandard: '',
        qualityLevel: ''
      },
      // 表单校验规则
      rules: {
        productName: [
          { required: true, message: '请输入产品名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        batchNumber: [
          { required: true, message: '请输入批次号', trigger: 'blur' }
        ],
        plantingDate: [
          { required: true, message: '请选择种植日期', trigger: 'change' }
        ],
        harvestDate: [
          { required: true, message: '请选择采收日期', trigger: 'change' }
        ],
        plantingArea: [
          { required: true, message: '请输入种植面积', trigger: 'blur' }
        ],
        qualityLevel: [
          { required: true, message: '请选择品质等级', trigger: 'change' }
        ]
      },
      // 溯源码对话框显示状态
      qrCodeVisible: false,
      // 当前产品
      currentProduct: {},
      // 当前用户ID
      userId: null,
      // 上传地址
      uploadUrl: process.env.VUE_APP_API_URL + '/file/upload',
      // 上传请求头
      uploadHeaders: {},
      // 溯源码URL
      qrCodeUrl: '',
      // 加载状态
      loading: false,
      submitting: false,
      qrCodeLoading: false,
      // 图片预览对话框
      imagePreviewVisible: false,
      previewImageUrl: '',
    }
  },
  created() {
    this.getUserInfo();
  },
  mounted() {
    this.getProductList();
    this.setUploadHeaders();
  },
  methods: {
    // 获取用户信息
    async getUserInfo() {
      try {
        const response = await userAPI.getUserInfo();
        this.userId = response.data.id;
      } catch (error) {
        console.error('Failed to fetch user info:', error);
        this.$message.error('获取用户信息失败');
      }
    },

    // 设置上传请求头
    setUploadHeaders() {
      const token = localStorage.getItem('token');
      if (token) {
        this.uploadHeaders = {
          'Authorization': `Bearer ${token}`
        };
      }
    },

    // 获取产品列表
    async getProductList() {
      try {
        this.loading = true;

        // 构建查询参数
        const params = {
          pageNum: this.queryParams.pageNum,
          pageSize: this.queryParams.pageSize,
          name: this.queryParams.productName,
          batchNumber: this.queryParams.batchNumber,
          farmerId: this.userId
        };

        // 添加日期范围参数
        if (this.queryParams.dateRange && this.queryParams.dateRange.length === 2) {
          params.startDate = this.queryParams.dateRange[0];
          params.endDate = this.queryParams.dateRange[1];
        }

        console.log("发送产品查询请求，参数：", params);
        const response = await productAPI.getProducts(params);
        console.log("获取产品列表响应:", response);

        if (response && response.code === 200) {
          // 详细记录返回的数据结构
          console.log("产品数据原始结构:", JSON.stringify(response.data));

          // 处理返回的数据
          const productData = response.data.list || response.data.content || response.data;

          // 确保productData是数组
          if (!Array.isArray(productData)) {
            console.error('产品数据不是数组:', productData);
            this.productList = [];
            this.total = 0;
            return;
          }

          // 进行日期格式化和字段映射
          this.productList = productData.map(item => {
            console.log("处理单个产品数据:", item);
            return {
              ...item,
              // 字段映射，确保显示正确
              name: item.name || item.productName,
              productCode: item.productCode,
              batchNumber: item.batchNumber || item.batchId,
              imageUrl: item.imageUrl || item.productImage, // 确保图片URL字段正确映射
              plantingDate: item.plantingDate ? this.formatDateToLocal(item.plantingDate) : '',
              harvestDate: item.harvestDate ? this.formatDateToLocal(item.harvestDate) : '',
              plantingArea: item.plantingArea || '',
              qualityLevel: item.qualityLevel || '',
              storageMethods: item.storageMethods || '',
              fertilizerUsed: item.fertilizerUsed || '',
              pesticideUsed: item.pesticideUsed || '',
              productionStandard: item.productionStandard || '',
              specification: "",
              unit: "斤"
            };
          });

          this.total = response.data.totalItems || response.data.totalElements || response.data.length || 0;
          console.log("处理后的产品列表数据:", this.productList);
        } else {
          console.error("获取产品列表失败:", response);
          this.$message.error('获取产品列表失败: ' + (response?.message || '未知错误'));
        }

        this.loading = false;
      } catch (error) {
        console.error('Failed to fetch product list:', error);
        this.$message.error('获取产品列表失败: ' + (error.message || '服务器错误，请稍后再试'));
        this.loading = false;
      }
    },

    // 搜索产品
    searchProduct() {
      this.queryParams.pageNum = 1;
      this.getProductList();
    },

    // 重置查询
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        productName: '',
        batchNumber: '',
        dateRange: []
      };
      this.getProductList();
    },

    // 处理每页数量变化
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getProductList();
    },

    // 处理页码变化
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getProductList();
    },

    // 打开添加对话框
    openAddDialog() {
      this.dialogTitle = '新增产品信息';
      this.resetForm();
      this.dialogVisible = true;
    },

    // 处理编辑
    async handleEdit(row) {
      try {
        console.log("开始获取产品详情，ID:", row.id);
        const response = await productAPI.getProductById(row.id);
        console.log("获取产品详情响应:", response);

        if (response && response.code === 200) {
          // 适配字段名称不同的问题
          const productData = response.data;
          this.productForm = {
            id: productData.id,
            productName: productData.productName,
            productCode: productData.productCode,
            batchNumber: productData.batchNumber || productData.batchId,
            plantingDate: productData.plantingDate,
            harvestDate: productData.harvestDate,
            plantingArea: productData.plantingArea,
            fertilizerUsed: productData.fertilizerUsed || productData.fertilizer,
            pesticideUsed: productData.pesticideUsed || productData.pesticide,
            storageMethods: productData.storageMethods,
            productImage: productData.productImage || productData.imageUrl,
            productionStandard: productData.productionStandard,
            qualityLevel: productData.qualityLevel
          };
          this.dialogTitle = '编辑产品信息';
          this.dialogVisible = true;
        } else {
          console.error("获取产品详情失败:", response);
          this.$message.error('获取产品详情失败: ' + (response?.message || '未知错误'));
        }
      } catch (error) {
        console.error('Failed to fetch product details:', error);
        this.$message.error('获取产品详情失败: ' + (error.message || '服务器错误'));
      }
    },

    // 处理删除
    handleDelete(row) {
      this.$confirm('确认删除该产品信息?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await productAPI.deleteProduct(row.id);
          this.$message.success('删除成功');
          this.getProductList();
        } catch (error) {
          console.error('Failed to delete product:', error);
          this.$message.error('删除产品失败');
        }
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },

    // 处理溯源码
    async handleQrCode(row) {
      this.currentProduct = row;
      this.qrCodeVisible = true;
      this.qrCodeLoading = true;
      this.qrCodeUrl = '';

      try {
        const response = await traceCodeAPI.generateTraceCode(row.batchNumber);
        this.qrCodeUrl = response.data.qrCodeUrl;
      } catch (error) {
        console.error('Failed to generate trace code:', error);
        this.$message.error('生成溯源码失败');
      } finally {
        this.qrCodeLoading = false;
      }
    },

    // 下载溯源码
    downloadQrCode() {
      if (this.qrCodeUrl) {
        const link = document.createElement('a');
        link.href = this.qrCodeUrl;
        link.download = `${this.currentProduct.productName}_${this.currentProduct.batchNumber}_溯源码.png`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      }
    },

    // 提交表单
    submitForm() {
      this.$refs.productFormRef.validate(async valid => {
        if (valid) {
          try {
            this.submitting = true;
            console.log("准备提交表单数据:", this.productForm);

            // 特别检查产品名称是否为空
            if (!this.productForm.productName || this.productForm.productName.trim() === '') {
              this.$message.error('产品名称不能为空');
              this.submitting = false;
              return;
            }

            // 确保批次号也不为空
            if (!this.productForm.batchNumber || this.productForm.batchNumber.trim() === '') {
              this.$message.error('批次号不能为空');
              this.submitting = false;
              return;
            }

            // 准备请求数据，适配后端API的字段名称
            const productData = {
              id: this.productForm.id,
              productName: this.productForm.productName,
              productCode: this.productForm.productCode,
              category: "枸杞",
              batchNumber: this.productForm.batchNumber,
              description: this.productForm.productName + "产品描述",
              imageUrl: this.productForm.productImage,
              farmerId: this.userId,
              createdAt: new Date().toISOString().slice(0, 19).replace('T', ' '),
              updatedAt: new Date().toISOString().slice(0, 19).replace('T', ' '),
              storageMethods: this.productForm.storageMethods || "",
              plantingDate: this.productForm.plantingDate || new Date().toISOString().slice(0, 19).replace('T', ' '),
              harvestDate: this.productForm.harvestDate || new Date().toISOString().slice(0, 19).replace('T', ' '),
              plantingArea: this.productForm.plantingArea || "",
              qualityLevel: this.productForm.qualityLevel || "",
              fertilizerUsed: this.productForm.fertilizerUsed || "",
              pesticideUsed: this.productForm.pesticideUsed || "",
              productionStandard: this.productForm.productionStandard || "",
              specification: "",
              unit: "斤"
            };

            console.log("提交的产品数据:", JSON.stringify(productData));

            if (this.productForm.id !== null) {
              // 编辑产品 - 使用正确的API路径
              console.log("正在更新产品，完整数据:", JSON.stringify(productData));

              // 添加所有现有产品信息，确保不会丢失字段
              const existingProduct = this.productList.find(p => p.id === this.productForm.id);
              if (existingProduct) {
                console.log("现有产品数据:", existingProduct);
                // 合并现有产品数据和新数据，确保所有必要字段都存在
                const completeProductData = {
                  ...existingProduct,
                  ...productData,
                  // 确保这些关键字段被包含和更新
                  name: productData.name,
                  productCode: productData.productCode,
                  batchNumber: productData.batchNumber,
                  category: productData.category,
                  description: productData.description,
                  imageUrl: productData.imageUrl,
                  farmerId: productData.farmerId,
                  updatedAt: new Date().toISOString().slice(0, 19).replace('T', ' ')
                };

                console.log("合并后的完整数据:", JSON.stringify(completeProductData));
                const updateResponse = await productAPI.updateProduct(`/${productData.id}`, completeProductData);
                console.log("更新产品响应:", updateResponse);

                if (updateResponse && updateResponse.code === 200) {
                  this.$message.success('修改成功');
                  this.dialogVisible = false;
                  this.getProductList();
                } else {
                  console.error("更新产品失败:", updateResponse);
                  this.$message.error('更新产品失败: ' + (updateResponse?.message || '未知错误'));
                }
              }
            } else {
              // 新增产品 - 使用正确的API路径
              console.log("正在新增产品，完整数据:", JSON.stringify(productData));
              const addResponse = await productAPI.addProduct(`/user/${this.userId}`, productData);
              console.log("添加产品响应:", addResponse);

              if (addResponse && addResponse.code === 200) {
                this.$message.success('新增成功');
                this.dialogVisible = false;
                this.getProductList();
              } else {
                console.error("新增产品失败:", addResponse);
                // 提取详细错误信息
                let errorMsg = '服务器错误';
                if (addResponse && addResponse.response && addResponse.response.data) {
                  console.error('错误响应详情:', addResponse.response.data);
                  errorMsg = addResponse.response.data.message || addResponse.response.data.error || '新增失败';
                } else if (addResponse && addResponse.message) {
                  errorMsg = addResponse.message;
                }
                this.$message.error('新增产品失败: ' + errorMsg);
              }
            }
          } catch (error) {
            console.error('Failed to save product:', error);
            // 提取详细错误信息
            let errorMsg = '服务器错误';
            console.error('Error response:', error.response);
            if (error.response && error.response.data) {
              console.error('错误响应详情:', JSON.stringify(error.response.data));
              errorMsg = error.response.data.message || error.response.data.error || '保存失败';
            } else if (error.message) {
              errorMsg = error.message;
            }
            this.$message.error('保存产品信息失败: ' + errorMsg);
          } finally {
            this.submitting = false;
          }
        } else {
          console.warn("表单验证失败");
          return false;
        }
      });
    },

    // 重置表单
    resetForm() {
      if (this.$refs.productFormRef) {
        this.$refs.productFormRef.resetFields();
      }
      this.productForm = {
        id: null,
        productName: '',
        productCode: '',
        batchNumber: '',
        plantingDate: '',
        harvestDate: '',
        plantingArea: '',
        fertilizerUsed: '',
        pesticideUsed: '',
        storageMethods: '',
        productImage: '',
        productionStandard: '',
        qualityLevel: ''
      };
    },

    // 格式化日期显示
    formatDate(dateStr) {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      if (isNaN(date.getTime())) return dateStr;

      return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    },

    // 格式化日期为本地格式
    formatDateToLocal(dateStr) {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      if (isNaN(date.getTime())) return dateStr;

      return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
      });
    },

    // 预览图片
    previewImage() {
      if (!this.productForm.productImage) {
        this.$message.warning('请先输入图片URL');
        return;
      }

      this.previewImageUrl = this.productForm.productImage;
      this.imagePreviewVisible = true;
    },

    // 显示大图
    showLargeImage(imageUrl) {
      this.previewImageUrl = imageUrl;
      this.imagePreviewVisible = true;
    },

    // 处理图片加载错误
    handleImageError(e) {
      // 设置默认图片
      e.target.src = require('@/assets/logo.png'); // 或者其他默认图片路径
      e.target.onerror = null; // 防止循环调用
    }
  }
}
</script>

<style scoped>
.info-entry-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-area {
  margin-bottom: 20px;
}

.product-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}

.product-uploader:hover {
  border-color: #409EFF;
}

.product-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.product-image {
  width: 178px;
  height: 178px;
  display: block;
}

.image-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.qrcode-container {
  text-align: center;
  padding: 20px 0;
}

.qrcode-image {
  margin-bottom: 15px;
}

.qrcode-image img {
  width: 200px;
  height: 200px;
}

.qrcode-info {
  margin-bottom: 15px;
}

.qrcode-info p {
  margin: 5px 0;
  color: #606266;
}

.qrcode-tip {
  font-size: 12px;
  color: #909399;
}

.image-preview {
  margin-top: 10px;
  width: 100%;
  display: flex;
  justify-content: center;
}

.product-image {
  max-width: 100%;
  max-height: 150px;
  border-radius: 4px;
  border: 1px solid #ebeef5;
}

.image-tip {
  font-size: 12px;
  margin-top: 5px;
  color: #909399;
}

.image-preview-container {
  text-align: center;
  padding: 20px 0;
}

.preview-image {
  max-width: 100%;
  max-height: 500px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.table-image-container {
  width: 60px;
  height: 60px;
  overflow: hidden;
  border-radius: 4px;
  margin: 0 auto;
  cursor: pointer;
  border: 1px solid #EBEEF5;
  transition: all 0.3s;
}

.table-image-container:hover {
  transform: scale(1.05);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.table-product-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style>
